import pytz
from datetime import datetime, time

from odoo import fields, models
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT


class SExportPurchaseStatementWizard(models.TransientModel):
    _name = 's.export.purchase.statement.wizard'

    partner_id = fields.Many2one('res.partner', string='supplier')
    start_date = fields.Date('start date', required=True)
    end_date = fields.Date('end date', required=True)

    def action_download(self):
        start_datetime_local = datetime.combine(self.start_date, time.min)
        end_datetime_local = datetime.combine(self.end_date, time.max)

        # 转换为 UTC 字符串
        tz_name = self._context.get('tz') or self.env.user.tz or 'UTC'
        local_tz = pytz.timezone(tz_name)
        utc_tz = pytz.timezone('UTC')

        start_localized = local_tz.localize(start_datetime_local)
        end_localized = local_tz.localize(end_datetime_local)

        start_utc = start_localized.astimezone(utc_tz)
        end_utc = end_localized.astimezone(utc_tz)

        return {
            'type': 'ir.actions.act_url',
            'url': '/download/purchase/reconciliation/excel/%s/%s/%s' % (
                self.partner_id.id or '0',
                start_utc.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
                end_utc.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            ),
            'target': 'new',
        }
